/*
 * *
 *  * Created with IntelliJ RustRover.
 *  * Description:
 *  * Copyright Author: ZhenYi
 *  * DateTime: 2024/2/15 下午6:47
 *
 */

use salvo::prelude::*;
use sea_orm::{DbBackend, FromQueryResult, JsonValue, Statement};
use sea_orm::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
pub struct UserNumsInput {
    pub genre: String,
}

#[handler]
pub async fn get_user_nums(
    req: &mut Request, depot: &mut Depot, res: &mut Response
){
    let db = depot.obtain::<DatabaseConnection>().unwrap();
    let input = match req.parse_json::<UserNumsInput>().await{
        Ok(input) => input,
        Err(e) => {
            res.status_code(StatusCode::IM_USED).render(e.to_string());
            return;
        }
    };

    if input.genre == "-1".to_string() {
        let unique: Vec<JsonValue> = JsonValue::find_by_statement(Statement::from_sql_and_values(
            DbBackend::Postgres,
            r#" select count(id) from userlist;"#,
            [],
        ))
            .all(db)
            .await.unwrap();

        res.status_code(StatusCode::ACCEPTED).render(
            &unique[0]
                .as_object()
                .unwrap()
                .get("count")
                .unwrap()
                .as_number()
                .unwrap()
                .as_i64()
                .unwrap()
                .to_string()
        );
        return;
    } else {
        let sql = format!(r#" select count(id) from userlist where genre = {};"#, input.genre);
        let unique: Vec<JsonValue> = JsonValue::find_by_statement(Statement::from_sql_and_values(
            DbBackend::Postgres,
            sql,
            [],
        ))
            .all(db)
            .await.unwrap();

        res.status_code(StatusCode::ACCEPTED).render(
            &unique[0]
                .as_object()
                .unwrap()
                .get("count")
                .unwrap()
                .as_number()
                .unwrap()
                .as_i64()
                .unwrap()
                .to_string()
        );
        return;
    }
}